﻿using System;
using System.Net.Http;

namespace Murry.DataStore.WebApiDB
{
    /// <summary>
    /// Web API implementation of IDataStore
    /// </summary>
    public abstract class WebApiDataStore : ReadOnlyDataStore<string>
    {
        /// <summary>
        /// Construct with a URI string.
        /// </summary>
        /// <param name="uriBase">URI base.</param>
        protected WebApiDataStore(string uriBase)
        {
            Database = uriBase;
        }

        /// <summary>
        /// Get object of type T from formatted uri string and values.
        /// </summary>
        /// <typeparam name="T">Type to retrieve.</typeparam>
        /// <param name="uri">URI format string.</param>
        /// <param name="values">Format values.</param>
        /// <returns>An object of type T.</returns>
        public static T GetFromUri<T>(string uri, params object[] values)
        {
            var newUri = String.Format(uri, values);
            using (var client = new HttpClient())
            {
                using (var response = client.GetAsync(newUri).Result)
                {
                    return response.Content.ReadAsAsyncIgnoreXmlEncoding<T>().Result;
                }
            }
        }

    }
}

